package com.roc.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
/**
 * 一一卡接口
* @Title: HttpClientUtil.java 
* @Package com.roc.util 
* @Description: TODO 
* @author dk
* @version V1.0
 */
public class HttpClientUtil {	
	static Logger logger=LogManager.getLogger(HttpClientUtil.class);	
	static int TIME=60000;
	/**
	 * HTTP发送JSON请求
	 * @param object
	 * @return
	 */
	public static JSONObject HttpRequstJSON(Object object,String url)
	{
		HttpClient client=null;
		PostMethod method=null;
		RequestEntity entity=null;
		InputStream in=null;
		BufferedReader br=null;
		JSONObject responseJson=null,requestJson=null;
		try {
			client=new HttpClient();
			//连接超时
			client.getHttpConnectionManager().getParams().setConnectionTimeout(TIME);
			//设置请求超时的时间
			client.getHttpConnectionManager().getParams().setSoTimeout(TIME);
			method=new PostMethod(url);
			requestJson=JSONObject.fromObject(object);
			String params=requestJson.toString();
			logger.info(params);
			if(params!=null && !params.trim().equals(""))
			{
					entity=new StringRequestEntity(params, "application/json", "UTF-8");
					method.setRequestEntity(entity);
				}
			//使用系统提供的默认的恢复策略
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
            //设置请求超时的时间
            int statusCode = client.executeMethod(method);
            //只要在获取源码中，服务器返回的不是200代码，则统一认为抓取源码失败，返回null。
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("请求失败: " + method.getStatusLine() + ",状态码: " + statusCode);
                return null;
            }
            //字符串获取
            //String responses= method.getResponseBodyAsString();
            //通过流获取
            in=method.getResponseBodyAsStream();
            br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            String response="",temp=null;
            while((temp=br.readLine())!=null)
            {
            	response=response+temp;
            }           
            logger.info(response);
            responseJson=JSONObject.fromObject(response);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}finally{
			try {
				if(br!=null)
				{
					br.close();
				}
				if(in!=null)
				{
					in.close();
				}
				if(method!=null)
				{
					//释放http连接
		            method.releaseConnection();
				}
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return responseJson;	
	}
	/**
	 * httpClient POST提交 NameValuePair
	 * @param map
	 * @return
	 */
	public static JSONObject QRcode(NameValuePair[] nameValuePair,String url)
	{
		HttpClient client=null;
		PostMethod method=null;
		InputStream in=null;
		BufferedReader br=null;
		JSONObject responseJson=null;
		if(nameValuePair!=null)
		{
			try{
				StringBuffer sb=new StringBuffer();
				for(int i=0;i<nameValuePair.length;i++){
					sb.append("[KEY-"+nameValuePair[i].getName()+",value-"+nameValuePair[i].getValue()+"]");
				}
				logger.info(sb.toString());
				client=new HttpClient();
				//连接超时
				client.getHttpConnectionManager().getParams().setConnectionTimeout(TIME);
				//设置请求超时的时间
				client.getHttpConnectionManager().getParams().setSoTimeout(TIME);
				method=new PostMethod(url);
				method.setRequestBody(nameValuePair);
				//使用系统提供的默认的恢复策略
	            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());	            
	            int statusCode = client.executeMethod(method);
	            //只要在获取源码中，服务器返回的不是200代码，则统一认为抓取源码失败，返回null。
	            if (statusCode != HttpStatus.SC_OK) {
	                logger.error("请求失败: " + method.getStatusLine() + ",状态码: " + statusCode);
	                return null;
	            }
	            in=method.getResponseBodyAsStream();
	            br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
	            String response="",temp=null;
	            while((temp=br.readLine())!=null)
	            {
	            	response=response+temp;
	            }
	            logger.info(response);
	            responseJson=JSONObject.fromObject(response);
			 } catch (Exception e) {
				 logger.error(e.getMessage(), e);
			 }finally{
				 try {
						if(br!=null)
						{
							br.close();
						}
						if(in!=null)
						{
							in.close();
						}
						if(method!=null)
						{
							//释放http连接
				            method.releaseConnection();
						}
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
			 }
		}
		return responseJson;
		
	}
}
